import React, { Component } from "react";
import { NavBar, Icon, Tabs, Toast, WhiteSpace, Badge } from "antd-mobile";
import SearchInput from "../searchInput/searchInput";

import myaxios from "../../utils/myaxios";
import emptyProduct from "../../assets/images/empty_product.jpg";
import "./GoodList.scss";
export default class GoodList extends Component {
  constructor(props) {
    super(props);
    // 列表的引用
    // 创建可直接访问dom节点的属性
    this.goodListRef = React.createRef();
    this.pagesize = 10; // 默认返回的每条请求的数量
    this.pagenum = 1; //
  }
  state = {
    tabs: [{ title: "综合" }, { title: "销量" }, { title: "价格" }],
    goods: [],
  };

  componentDidMount() {
    let { search } = this.props.location;
    let params = search.split('?')[1] || "";
    let params_arr = params.split('=');
    if (params_arr[0] === 'cid') {
      this.cid = params_arr[1]
    } else if (params_arr[0] === 'query') {
      this.query = params_arr[1]
    }

    this.getProductList();

    console.log(this.goodListRef.current)
    this.goodListRef.current.parentElement.addEventListener(
      "scroll",
      this.handleScroll
    );

  }
  /* 获取产品的列表 */
  getProductList = () => {
    // 拼接参数
    let params = {};
    if (this.cid) {
      params['cid'] = this.cid
    }
    if (this.query) {
      params['query'] = decodeURIComponent(this.query)
    }
    // 如果页码存在
    if (this.total) {
      params['pagenum'] = ++this.pagenum
    } else {
      params['pagenum'] = this.pagenum
    }
    // 默认的页码
    params['pagesize'] = this.pagesize
    // 如果当前的页码大于总页码
    if (this.pagenum > Math.ceil(this.total / this.pagesize)) {
      Toast.info('已经是最后一条数据了', 1)
    } else {
      myaxios.get('goods/search', {
        params,
      }).then((res) => {
        this.total = res.total;
        this.pagenum = res.pagenum;
        this.setState({
          goods: [...this.state.goods, ...res.goods],
        })
      })
        .catch((err) => {
          console.log(err)
        })
    }
  }

  handleScroll = () => {
    console.log("列表开始滚动拉");
    let parentElement = this.goodListRef.current.parentElement;
    // 客户端的高度 clientHeight
    let clientHeight = parentElement.clientHeight;

    //列表的高度
    let scrollHeight = parentElement.scrollHeight;

    // 列表已经滚动的高度
    let scrollTop = parentElement.scrollTop;
    
    // 如果结果小于或者等于1 说明已经触底
    // scrollHeight=clientHeight+scrollTop
    // 总的可以滚动的距离 = 可视距离 + 已滚动距离
    // 发请求 或者最新的列表数据
    if (scrollHeight - clientHeight - scrollTop <= 1) {
      console.log("触底拉");
      this.getProductList();
    }
  };

  componentWillUnmount() {
    // 卸载监听事件
    this.goodListRef.current.parentElement.removeEventListener(
      "scroll",
      this.handleScroll
    );
  }

  handleItemClick = (goods_id) => {
    this.props.history.push("/goodDetail/" + goods_id);
  };

  render() {
    return (
      <div className="yg-gl">
        {/* 商品列表导航条开始 */}
        <div className="yg-gl-nav">
          <NavBar
            className="gl-nav"
            icon={<Icon type="left" />}
            onLeftClick={() => window.history.go(-1)}
          >
            商品列表
          </NavBar>
        </div>
        {/* 商品列表导航条结束 */}
        {/* 商品列表搜索框开始 */}
        <div className="yg-gl-search">
          <SearchInput></SearchInput>
        </div>
        {/* 商品列表搜索框结束 */}

        {/* tab切换栏开始 */}
        <div>
          <Tabs tabs={this.state.tabs}
            initialPage={1}
            onChange={(tab, index) => { console.log('onChange', index, tab); }}
            onTabClick={(tab, index) => { console.log('onTabClick', index, tab); }}
            tabBarUnderlineStyle={{ borderColor: "red" }}
            tabBarTextStyle={{ fontWeight: "200", color: "black" }}
          >
            <div className="gl-tab-zh" ref={this.goodListRef} style={{height: `calc(100vh - 3.466667rem)`}}>
              {this.state.goods.map((v, index) => {
                return (
                  <div
                    className="tab-zh-item"
                    style={{
                      display: 'flex',
                      height: '3.2rem',
                      alignItems: 'center',
                      padding: '0.133333rem',
                      borderBottom: '1px solid #ddd'
                    }}
                    key={v.goods_id}
                    onClick={this.handleItemClick.bind(this, v.goods_id)}
                  >
                    <div className="zh-item-left">
                      <img
                        style={{
                          width: '2.666667rem',
                          height: '2.666667rem'
                        }}
                        src={
                          v.goods_small_logo ? v.goods_small_logo : emptyProduct
                        }
                        alt=""
                      />
                    </div>
                    <div
                      className="zh-item-right"
                      style={{
                        display: 'flex',
                        flexDirection: 'column',
                        justifyContent: 'space-around',
                        height: '3.2rem',
                        marginLeft: '0.133333rem'
                      }}
                    >
                      <div className="item-right-top">{v.goods_name}</div>
                      <div
                        className="item-right-bottom"
                        style={{ color: `var(--themeColor)` }}
                      >￥{v.goods_price}</div>
                    </div>
                  </div>
                );
              })}
            </div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '150px', backgroundColor: '#fff' }}>
              销量
            </div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '150px', backgroundColor: '#fff' }}>
              价格
            </div>
          </Tabs>
          <WhiteSpace />
        </div>
        {/* tab切换栏结束 */}
      </div>
    );
  }
}